/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package tableprocessor;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.PrintStream;
import javax.swing.JTextArea;

/**
 *
 * @author gleb
 */
public class StaticLogContainer implements Runnable{
    JTextArea displayPane;
    BufferedReader reader;

    private StaticLogContainer(JTextArea displayPane, PipedOutputStream pos)
    {
        this.displayPane = displayPane;

        try
        {
            PipedInputStream pis = new PipedInputStream( pos );
            reader = new BufferedReader( new InputStreamReader(pis) );
        }
        catch(IOException e) {}
    }

    public void run()
    {
        String line = null;

        try
        {
            while ((line = reader.readLine()) != null)
            {
//              displayPane.replaceSelection( line + "\n" );
                displayPane.append( line + "\n" );
                displayPane.setCaretPosition( displayPane.getDocument().getLength() );
            }

        }
        catch (IOException ioe)
        {

        }
    }

    public static void redirectOutput(JTextArea displayPane)
    {
        StaticLogContainer.redirectOut(displayPane);
        StaticLogContainer.redirectErr(displayPane);
    }

    public static void redirectOut(JTextArea displayPane)
    {
        PipedOutputStream pos = new PipedOutputStream();
        System.setOut( new PrintStream(pos, true) );

        StaticLogContainer console = new StaticLogContainer(displayPane, pos);
        new Thread(console).start();
    }

    public static void redirectErr(JTextArea displayPane)
    {
        PipedOutputStream pos = new PipedOutputStream();
        System.setErr( new PrintStream(pos, true) );

        StaticLogContainer console = new StaticLogContainer(displayPane, pos);
        new Thread(console).start();
    }
}
